package in.muton.edushare.pages.univ;

import in.muton.edushare.components.messaging.api.UserMessage;
import in.muton.edushare.processing.objects.UnivDataHandler;
import in.muton.edushare.wicket.models.CayenneList;

import java.util.Arrays;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.dao.AcademicYearModelDAO;
import com.edushare.common.dao.UsersDAO;
import com.edushare.common.vo.Messages;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.UserRoles;
import com.edushare.common.vo.Users;

public class UnivSemControl extends UnivBase {

	public static Log log = LogFactory.getLog(UnivSemControl.class);

	public UnivSemControl(PageParameters params) {
		super(params);
		prc.check(Arrays.asList(UserRoles.ADMIN_ROLE));
		addVerifier();
		addSemChangeScheduled();
		addChangeSemForm();
		addElectiveClose();
		addLockChoiceMessage();

		add(new Label("semName", new Model<String>() {
			private static final long serialVersionUID = 1L;

			@Override
			public String getObject() {
				String sem = new AcademicYearModelDAO(getSessionORMInterface(),
						getModel().getObject()).getActiveSemester()
						.getSemesterName();
				return sem + ", " + getModel().getObject().getCurrentAcadYear()
						+ "-"
						+ (getModel().getObject().getCurrentAcadYear() + 1);
			}
		}));
	}

	private void addVerifier() {
		WebMarkupContainer wmc = new WebMarkupContainer("verification") {
			private static final long serialVersionUID = 711780998925718178L;

			@Override
			public boolean isVisible() {
				return !isAuthenticated;
			}
		};
		add(wmc);
		Form<Void> f = new Form<Void>("verification") {
			private static final long serialVersionUID = -2811791828958422680L;

			@Override
			public void onSubmit() {
				Users u = new UsersDAO(getSessionORMInterface())
						.getAuthenticUser(getLoggedInUser().getUserName(),
								getPassword());
				if (u != null) {
					isAuthenticated = true;
					clearError();
				} else {
					setErrorMessage("The password you provided is incorrect.");
				}
			}
		};
		wmc.add(f);
		f.add(new PasswordTextField("password", new PropertyModel<String>(this,
				"password")));
		f.add(new Button("submit"));
	}

	private void addChangeSemForm() {
		WebMarkupContainer wmc = new WebMarkupContainer("changeSemester") {
			private static final long serialVersionUID = 711780998925718178L;

			@Override
			public boolean isVisible() {
				return isAuthenticated
						&& getModel().getObject().getElectiveSelectionTime() == Universities.UNIV_CLOSE_ELECTIVE_SELECTION;
			}
		};
		add(wmc);
		Form<Void> f = new Form<Void>("semesterForm") {
			private static final long serialVersionUID = 3528523136287404070L;

			@Override
			public void onSubmit() {
				IModel<Universities> currModel = UnivSemControl.this.getModel();
				currModel.getObject().setElectiveSelectionTime(
						Universities.UNIV_SCHEDULE_SEMESTER_CHANGE);
				String semName = new AcademicYearModelDAO(
						getSessionORMInterface(), currModel.getObject())
						.getActiveSemester().getSemesterName();
				String message = "The semester "
						+ semName
						+ ", "
						+ currModel.getObject().getCurrentAcadYear()
						+ " will be closed tonight."
						+ " Students will be assigned to their courses for the next semester and will be able to choose electives at that time.";
				CayenneList<Users> userList = new UnivDataHandler(currModel)
						.getEveryOne();

				log.debug("About to send message \n" + message);
				new UserMessage(message).setReciever(userList).setReciever(
						currModel.getObject()).setPrivacy(
						Messages.PRIVACY_TYPE_PUBLIC).send();
				getSessionORMInterface().commitAllChanges();
			}
		};
		wmc.add(f);
		f.add(new Button("semester"));
	}

	private void addSemChangeScheduled() {
		WebMarkupContainer wmc = new WebMarkupContainer("semChangeScheduled") {
			@Override
			public boolean isVisible() {
				return isAuthenticated
						&& getModel().getObject().getElectiveSelectionTime() == Universities.UNIV_SCHEDULE_SEMESTER_CHANGE;
			}

			private static final long serialVersionUID = 4598591620440214073L;
		};
		add(wmc);
	}

	private void addElectiveClose() {
		WebMarkupContainer wmc = new WebMarkupContainer("choiceClose") {
			private static final long serialVersionUID = 711780998925718178L;

			@Override
			public boolean isVisible() {
				return isAuthenticated
						&& getModel().getObject().getElectiveSelectionTime() == Universities.UNIV_ALLOW_ELECTIVE_SELECTION;
			}
		};
		add(wmc);
		Form<Void> f = new Form<Void>("semesterForm") {
			private static final long serialVersionUID = -2811791828958422680L;

			@Override
			public void onSubmit() {
				IModel<Universities> currModel = UnivSemControl.this.getModel();
				String semName = new AcademicYearModelDAO(
						getSessionORMInterface(), currModel.getObject())
						.getActiveSemester().getSemesterName();
				String message = "Elective choosing time for semester "
						+ semName
						+ ", "
						+ currModel.getObject().getCurrentAcadYear()
						+ " has been closed."
						+ " Students will be assigned to their electives at midnight.";
				CayenneList<Users> userList = new UnivDataHandler(currModel)
						.getEveryOne();

				log.debug("About to send message \n" + message);
				new UserMessage(message).setReciever(userList).setReciever(
						currModel.getObject()).setPrivacy(
						Messages.PRIVACY_TYPE_PUBLIC).send();
				UnivSemControl.this.getModel().getObject()
						.setElectiveSelectionTime(
								Universities.UNIV_LOCK_ELECTIVE_SELECTION);
				getSessionORMInterface().commitAllChanges();
			}
		};
		wmc.add(f);
		f.add(new Button("semester"));
	}

	private void addLockChoiceMessage() {
		add(new WebMarkupContainer("lockChoices") {
			private static final long serialVersionUID = 4461577230960709085L;

			@Override
			public boolean isVisible() {
				return isAuthenticated
						&& getModel().getObject().getElectiveSelectionTime() == Universities.UNIV_LOCK_ELECTIVE_SELECTION;
			}
		});
	}

	@Override
	public String getActivePage(PageParameters p) {
		return "SemesterControl";
	}

	@Override
	public String getPageTitle() {
		return getLoggedInUser().getCompleteUserName() + " | "
				+ getModel().getObject().getUniversityName()
				+ " | Semester control panel | "
				+ ApplicationConstants.APPLICATION_NAME;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}

	private boolean isAuthenticated = false;
	private String password = "";
}
